package com.knowledge.common.utils;

import java.util.*;

import com.aliyun.searchplat20240529.Client;
import com.aliyun.searchplat20240529.models.GetDocumentSplitRequest;
import com.aliyun.searchplat20240529.models.GetDocumentSplitResponse;
import com.aliyun.searchplat20240529.models.GetDocumentSplitResponseBody;
import com.aliyun.teaopenapi.models.Config;

import com.aliyun.searchplat20240529.Client;
import com.aliyun.searchplat20240529.models.GetDocumentSplitRequest;
import com.aliyun.searchplat20240529.models.GetDocumentSplitResponse;
import com.aliyun.teaopenapi.models.Config;


/**
 * 文档切片工具类
 * 支持调用AI搜索开放平台的文档切片服务
 *
 * @author knowledge
 */
public class AliYunDocumentSplitUtils {

    // API配置信息
    private static final String API_KEY = "Bearer OS-c8465ieux1wpv3qt"; // 替换为实际的API Key
    private static final String HOST = "http://default-23k7.platform-cn-shanghai.opensearch.aliyuncs.com"; // 替换为实际的服务地址
    private static final String WORKSPACE_NAME = "default"; // 替换为实际的工作空间名称
    private static final String SERVICE_ID = "ops-document-split-001";


    /**
     * 对文本内容进行文档切片（带策略配置）
     *
     * @param content 需要切片的文本内容
     * @return 切片结果
     */
    public static List<GetDocumentSplitResponseBody.GetDocumentSplitResponseBodyResultChunks> splitDocument(String content, String documentType) throws Exception {
        Config config = new Config();
        config.setBearerToken("OS-c8465ieux1wpv3qt");
        config.setEndpoint("default-23k7.platform-cn-shanghai.opensearch.aliyuncs.com");
        config.setProtocol("http");
        Client client = new Client(config);

        GetDocumentSplitRequest request = GetDocumentSplitRequest.build(new HashMap<String, Map<String, Object>>() {{
            put("document", new HashMap<String, Object>() {{
                put("content", content);
                if (!"3".equals(documentType)) {
                    put("content_type", "text");
                } else {
                    put("content_type", "html");
                }

            }});
            put("strategy", new HashMap<String, Object>() {{
                put("max_chunk_size", 150);
                put("need_sentence", false);
            }});
        }});
        List<GetDocumentSplitResponseBody.GetDocumentSplitResponseBodyResultChunks> chunks = new ArrayList<>();
        GetDocumentSplitResponse response = client.getDocumentSplit("default", "ops-document-split-001", request);
        Integer statusCode = response.getStatusCode();
        if (200 == statusCode) {
            System.out.println(Arrays.toString(response.getBody().getResult().getChunks().stream().map(chunk -> chunk.getContent()).toArray()));
            chunks = response.getBody().getResult().getChunks();
        } else {
            throw new RuntimeException("文档切片请求失败，状态码: " + response.getStatusCode());
        }
        return chunks;


//        Document document = new Document(content);
//        RequestBody requestBody = new RequestBody(document, strategy);
//        // 构建请求URL
//        String url = HOST + "/v3/openapi/workspaces/" + WORKSPACE_NAME + "/document-split/" + SERVICE_ID;
//        // 设置请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.set("Authorization", API_KEY);
//        // 创建请求实体
//        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(requestBody), headers);
//
//        // 发送请求
//        RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
//        // 解析响应
//        if (response.getStatusCode().is2xxSuccessful()) {
//            JSONObject jsonObject = JSON.parseObject(response.getBody());
//            JSONObject result = jsonObject.getJSONObject("result");
//            DocumentSplitResult splitResult = new DocumentSplitResult();
//            // 解析chunks
//            if (result.containsKey("chunks")) {
//                List<Chunk> chunks = new ArrayList<>();
//                for (Object obj : result.getJSONArray("chunks")) {
//                    JSONObject chunkJson = (JSONObject) obj;
//                    Chunk chunk = new Chunk();
//                    chunk.setContent(chunkJson.getString("content"));
//                    // 修复getInnerMap()方法不存在的问题
//                    Map<String, Object> meta = new HashMap<>();
//                    JSONObject metaJson = chunkJson.getJSONObject("meta");
//                    if (metaJson != null) {
//                        for (String key : metaJson.keySet()) {
//                            meta.put(key, metaJson.get(key));
//                        }
//                    }
//                    chunk.setMeta(meta);
//                    chunks.add(chunk);
//                }
//                splitResult.setChunks(chunks);
//            }
//
//
//            // 解析nodes
//            if (result.containsKey("nodes")) {
//                List<Node> nodes = new ArrayList<>();
//                for (Object obj : result.getJSONArray("nodes")) {
//                    JSONObject nodeJson = (JSONObject) obj;
//                    Node node = new Node();
//                    node.setId(nodeJson.getString("id"));
//                    node.setType(nodeJson.getString("type"));
//                    node.setContent(nodeJson.getString("content"));
//                    // 修复getInnerMap()方法不存在的问题
//                    Map<String, Object> meta = new HashMap<>();
//                    JSONObject metaJson = nodeJson.getJSONObject("meta");
//                    if (metaJson != null) {
//                        for (String key : metaJson.keySet()) {
//                            meta.put(key, metaJson.get(key));
//                        }
//                    }
//                    node.setMeta(meta);
//                    // 修复空指针异常：在调用toJavaList前检查数组是否为空
//                    List<String> childrenList = new ArrayList<>();
//                    if (nodeJson.getJSONArray("children") != null) {
//                        childrenList = nodeJson.getJSONArray("children").toJavaList(String.class);
//                    }
//                    node.setChildren(childrenList);
//                    nodes.add(node);
//                }
//                splitResult.setNodes(nodes);
//            }
//            // 解析richTexts
//            if (result.containsKey("rich_texts")) {
//                List<RichText> richTexts = new ArrayList<>();
//                for (Object obj : result.getJSONArray("rich_texts")) {
//                    JSONObject richTextJson = (JSONObject) obj;
//                    RichText richText = new RichText();
//                    richText.setContent(richTextJson.getString("content"));
//                    // 修复getInnerMap()方法不存在的问题
//                    Map<String, Object> meta = new HashMap<>();
//                    JSONObject metaJson = richTextJson.getJSONObject("meta");
//                    if (metaJson != null) {
//                        for (String key : metaJson.keySet()) {
//                            meta.put(key, metaJson.get(key));
//                        }
//                    }
//                    richText.setMeta(meta);
//                    richTexts.add(richText);
//                }
//                splitResult.setRichTexts(richTexts);
//            }
//            // 解析sentences
//            if (result.containsKey("sentences")) {
//                List<Sentence> sentences = new ArrayList<>();
//                for (Object obj : result.getJSONArray("sentences")) {
//                    JSONObject sentenceJson = (JSONObject) obj;
//                    Sentence sentence = new Sentence();
//                    sentence.setContent(sentenceJson.getString("content"));
//                    // 修复getInnerMap()方法不存在的问题
//                    Map<String, Object> meta = new HashMap<>();
//                    JSONObject metaJson = sentenceJson.getJSONObject("meta");
//                    if (metaJson != null) {
//                        for (String key : metaJson.keySet()) {
//                            meta.put(key, metaJson.get(key));
//                        }
//                    }
//                    sentence.setMeta(meta);
//                    sentences.add(sentence);
//                }
//                splitResult.setSentences(sentences);
//            }


    }

    /**
     * 提取可用于embedding的文档片段
     *
     * @param splitResult 切片结果
     * @return 文档片段列表
     */
//    public static List<Map<String, String>> extractEmbeddingDocuments(DocumentSplitResult splitResult) {
//        List<Map<String, String>> docList = new ArrayList<>();
//
//        // 从chunks中提取
//        if (splitResult.getChunks() != null) {
//            for (Chunk chunk : splitResult.getChunks()) {
//                Map<String, String> doc = new HashMap<>();
//                doc.put("id", (String) chunk.getMeta().get("id"));
//                doc.put("content", chunk.getContent());
//                docList.add(doc);
//            }
//        }
//
//        // 从richTexts中提取（排除图片）
//        if (splitResult.getRichTexts() != null) {
//            for (RichText richText : splitResult.getRichTexts()) {
//                String type = (String) richText.getMeta().get("type");
//                if (!"image".equals(type)) {
//                    Map<String, String> doc = new HashMap<>();
//                    doc.put("id", (String) richText.getMeta().get("id"));
//                    doc.put("content", richText.getContent());
//                    docList.add(doc);
//                }
//            }
//        }
//
//        return docList;
//    }


    /**
     * private static final String accessKeyId = "LTAI5tFSpEuFVeCj8CVqGFCU";
     * private static final String accessKeySecret = "Vsvs9UcVfF1kiBL9LDthKg5WwP9aQS";
     * <p>
     * <p>
     * 文档切片结果类
     */
//    public static class DocumentSplitResult {
//        private List<Chunk> chunks;
//        private List<Node> nodes;
//        private List<RichText> richTexts;
//        private List<Sentence> sentences;
//
//        // Getters and setters
//        public List<Chunk> getChunks() {
//            return chunks;
//        }
//
//        public void setChunks(List<Chunk> chunks) {
//            this.chunks = chunks;
//        }
//
//        public List<Node> getNodes() {
//            return nodes;
//        }
//
//        public void setNodes(List<Node> nodes) {
//            this.nodes = nodes;
//        }
//
//        public List<RichText> getRichTexts() {
//            return richTexts;
//        }
//
//        public void setRichTexts(List<RichText> richTexts) {
//            this.richTexts = richTexts;
//        }
//
//        public List<Sentence> getSentences() {
//            return sentences;
//        }
//
//        public void setSentences(List<Sentence> sentences) {
//            this.sentences = sentences;
//        }
//    }


    /**
     * 节点类
     */
    public static class Node {
        private String id;
        private String type;
        private String content;
        private Map<String, Object> meta;
        private List<String> children;

        // Getters and setters
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public Map<String, Object> getMeta() {
            return meta;
        }

        public void setMeta(Map<String, Object> meta) {
            this.meta = meta;
        }

        public List<String> getChildren() {
            return children;
        }

        public void setChildren(List<String> children) {
            this.children = children;
        }
    }

    /**
     * 富文本类
     */
    public static class RichText {
        private String content;
        private Map<String, Object> meta;

        // Getters and setters
        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public Map<String, Object> getMeta() {
            return meta;
        }

        public void setMeta(Map<String, Object> meta) {
            this.meta = meta;
        }
    }

    /**
     * 句子类
     */
    public static class Sentence {
        private String content;
        private Map<String, Object> meta;

        // Getters and setters
        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public Map<String, Object> getMeta() {
            return meta;
        }

        public void setMeta(Map<String, Object> meta) {
            this.meta = meta;
        }
    }

    /**
     * 策略配置类
     */
    public static class Strategy {
        private String type = "default";
        private Integer maxChunkSize = 300;
        private String computeType = "token";
        private Boolean needSentence = false;

        // Getters and setters
        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public Integer getMaxChunkSize() {
            return maxChunkSize;
        }

        public void setMaxChunkSize(Integer maxChunkSize) {
            this.maxChunkSize = maxChunkSize;
        }

        public String getComputeType() {
            return computeType;
        }

        public void setComputeType(String computeType) {
            this.computeType = computeType;
        }

        public Boolean getNeedSentence() {
            return needSentence;
        }

        public void setNeedSentence(Boolean needSentence) {
            this.needSentence = needSentence;
        }
    }

    /**
     * 文档类
     */
    public static class Document {
        private String content;
        private String contentEncoding = "utf8";
        private String contentType = "text";

        public Document(String content) {
            this.content = content;
        }

        // Getters and setters
        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getContentEncoding() {
            return contentEncoding;
        }

        public void setContentEncoding(String contentEncoding) {
            this.contentEncoding = contentEncoding;
        }

        public String getContentType() {
            return contentType;
        }

        public void setContentType(String contentType) {
            this.contentType = contentType;
        }
    }

    /**
     * 请求体类
     */
    public static class RequestBody {
        private Document document;
        private Strategy strategy;

        public RequestBody(Document document, Strategy strategy) {
            this.document = document;
            this.strategy = strategy;
        }

        // Getters and setters
        public Document getDocument() {
            return document;
        }

        public void setDocument(Document document) {
            this.document = document;
        }

        public Strategy getStrategy() {
            return strategy;
        }

        public void setStrategy(Strategy strategy) {
            this.strategy = strategy;
        }
    }


}
